define(['app'], function(app) {
	'use strict';

	var controller = function controller($scope, Productsearch,GoDialog, $window, $stateParams, $ionicScrollDelegate, $ionicSideMenuDelegate, GoPage, Auth, $timeout, GoCatTypeAuth) {
		//接收参数
		$scope.input = new Object();
		function initialization(){
			$scope.sort = [{id:1,name:"默认排序"},{id:9,name:"总销量从高到低"},{id:7,name:"访问次数从高到低"},{id:2,name:"发布时间从新到旧"},{id:10,name:"评论次数从高到低"},{id:12,name:"店铺距离从近到远"},{id:13,name:"店铺距离从远到近"},{id:4,name:"价格从高到低"},{id:5,name:"价格从低到高"}];
			$scope.input.order_select = {id:1,name:"默认排序"};
			$scope.input.top_search_flag = $stateParams.top_search_flag; //0->买家/1->卖家
			$scope.input.st = $stateParams.st; //'g'->商品  'b'->品牌
			$scope.input.keywords = $stateParams.keywords;
//			console.log($stateParams)
			$scope.input.brand_id = $stateParams.brand_id; //品牌传递
			$scope.input.brand_name = $stateParams.brand_name; //品牌传递
			$scope.input.brand = {id:$stateParams.brand_id,name:$stateParams.brand_name==""?"请选择品牌":$stateParams.brand_name};
			$scope.input.cat_id = $stateParams.cat_id; //分类传递
			$scope.input.cat_name = $stateParams.cat_name; //分类传递
			$scope.input.product_display_rate = 1; //默认显示
			
			$scope.input.orderby = "1";
			$scope.input.showimg = 0; //0 列表模式 1图片模式
			$scope.input.xiaol = -1; //销量排序
			$scope.input.price = -1; //价格排序
			$scope.input.nPage = 1;
			//过度使用
			$scope.input.image_url = sessionStorage.getItem("img-search-url") == undefined ? '' : sessionStorage.getItem("img-search-url"); //默认显示
			$scope.input.goods_id_search = sessionStorage.getItem("goods_id_search") == undefined ? '' : sessionStorage.getItem("goods_id_search");//检索该商品
			$scope.input.goods_name = $stateParams.goods_name; //商品传递
		}
		$scope.doSelectSort = function(){
			//id是值 name是显示
			GoDialog.showSelect("请选择排序",$scope.sort,$scope.input.order_select,function(data){
				$scope.input.orderby = data.id;
				$scope.input.order_select = data;
			});
		}
		//用户状态
		$scope.$on('$ionicView.afterEnter', function() {
			GoPage.init_top($scope,44,0,79);
			initialization();//每次进来都初始化一次，否则每次进来看到的都是第一次进来时的画面
			$scope.init_auth(); //必须在定义之后
			$scope.init_search();
		}, false);
		
		$scope.init_auth = function() {
			$scope.user_type = Auth.check_user_type();
		};
		//分类id处理
		$scope.checkCateid = function() {
			if($scope.input.cat1 != null && $scope.input.cat1.id != 0)
				$scope.input.cat_id = $scope.input.cat1.id;
			if($scope.input.cat2 != null && $scope.input.cat2.id != 0)
				$scope.input.cat_id = $scope.input.cat2.id;
			if($scope.input.cat3 != null && $scope.input.cat3.id != 0)
				$scope.input.cat_id = $scope.input.cat3.id;
		};
		
		//初始化页面
		$scope.init_search = function() {
			$scope.checkCateid();
			var params = {
				top_search_flag: $scope.input.top_search_flag,
				st: $scope.input.st,
				scontent: $scope.input.keywords,
				brand_id: $scope.input.brand_id, //可能1级也可能2级
				cat_id: $scope.input.cat_id,
				orderby: $scope.input.orderby,
				nPage: $scope.input.nPage,
				image_url: $scope.input.image_url,
				goods_id_search: $scope.input.goods_id_search
			};
			//初始化
			Productsearch.search_getlist(params, function(data) {
//				console.log("初始化")
				if(data.result == null) {
					$scope.productsearch = new Array();
				} else {
					$scope.page = data.result.page;//控制html里的加载更多
					$scope.isShowPrice = data.result.price_label_show;//'true'->显示   'false'->不显示
					$scope.input.product_display_rate = data.result.product_display_rate; //默认显示
					$scope.productsearch = $scope.dochecklink(data.result).products;
				}
				$scope.initBrandsAndCat();//初始化品牌和第一级分类
			});
		};
		
		//搜索
		$scope.goto_search = function(callback) {
			$scope.input.nPage = 1;
			$scope.checkCateid();
			var params = {
				top_search_flag: $scope.input.top_search_flag,
				st: $scope.input.st,
				scontent: $scope.input.keywords,
				brand_id: $scope.input.brand?$scope.input.brand.id:0, //可能1级也可能2级
				cat_id: $scope.input.cat_id,
				orderby: $scope.input.orderby,
				nPage: $scope.input.nPage,
				image_url: $scope.input.image_url,
				goods_id_search: $scope.input.goods_id_search
			};
			Productsearch.search_getlist(params, function(data) {
				if(data.result == null) {
					$scope.productsearch = new Array();
				} else {
					$scope.input.product_display_rate = data.result.product_display_rate; //默认显示
					$scope.productsearch = $scope.dochecklink(data.result).products;
				}
			}, function() {
				if(callback)
					callback();
			});
			$ionicScrollDelegate.$getByHandle("main-handle").scrollTop(true);
		}
		$scope.goto_more_search = function(callback) {
			$scope.checkCateid();
			var params = {
				top_search_flag: $scope.input.top_search_flag,
				st: $scope.input.st,
				scontent: $scope.input.keywords,
				brand_id: $scope.input.brand_id, //可能1级也可能2级
				cat_id: $scope.input.cat_id,
				orderby: $scope.input.orderby,
				nPage: $scope.input.nPage + 1,
				image_url: $scope.input.image_url,
				goods_id_search: $scope.input.goods_id_search
			};
			Productsearch.search_getlist(params, function(data) {
//				console.log(data.result)
				if(data.result != null&&data.result.products) {
					$scope.input.nPage = $scope.input.nPage + 1;
					$scope.input.product_display_rate = data.result.product_display_rate; //默认显示
					$scope.productsearch = $scope.productsearch.concat($scope.dochecklink(data.result).products);
				}
			}, function() {
				if(callback)
					callback();
			});
		}
		//搜索
		$scope.do_search = function() {
			$scope.goto_search();
			$ionicSideMenuDelegate.toggleRight(false);
		};
		
		/***分类二级联动***/
		$scope.input.cat1 = { id: 0, name: "请选择大分类" };
		$scope.input.cat2 = { id: 0, name: "请选择中分类" };
		$scope.input.cat3 = { id: 0, name: "请选择小分类" };
		//下拉侦听
		$scope.listen_cat1 = function(data, obj) {
			$scope.input.cat2 = { id: 0, name: "请选择中分类" };
			$scope.input.cat3 = { id: 0, name: "请选择小分类" };
		};
		$scope.listen_cat2 = function(data, obj) {
			$scope.input.cat3 = { id: 0, name: "请选择小分类" };
		};
		//初始化品牌和分类
		$scope.initBrandsAndCat = function(){
			Productsearch.search_getbrand({}, function(data) {
				$scope.brand_items = data.result.brand;
				for(var i = 0; i < $scope.brand_items.length; i++) {
					if($scope.brand_items[i].id == $scope.input.brand_id) {
						$scope.input.brand = $scope.brand_items[i];
						break;
					}
				}
			});
			GoCatTypeAuth.init_load_only($scope, items_cat);
		}
		//初始化分类
		var items_cat = new Array();
		var obj1_cat = { name: 'input.cat1' };
		var obj2_cat = { name: 'input.cat2' };
		items_cat.push(obj1_cat);
		items_cat.push(obj2_cat);
		//最好不要直接写在这里，由于“goods.main.search”接口较慢，写在这里的话，goods.main.search还没请求完，加载状态的圈圈就隐藏了，造成用户体验不好
		//解决办法：放在初始化的回调函数里（测试：直接刷新浏览器是测不了的，因为有很多隐藏的全局方法请求接口，它们会触发$rootScope.$broadcast('loading:hide')，所以要回到首页进行搜索来测）
//		GoCatTypeAuth.init_load_only($scope, items_cat);
		if(parseInt($scope.input.cat_id) > 0) {
			GoCatTypeAuth.inti_cat($scope, $scope.input.cat_id, function(val1, val2, val3) {
				//使用定时器来指引
				$scope.isUnwatch = true; //不进行侦听操作
				$scope.input.cat1 = val1;
				$scope.input.cat2 = val2;
				$scope.input.cat3 = val3;
				$timeout(function() {
					$scope.isUnwatch = false; //不进行侦听操作
				}, 1000);
			});
		}
		$scope.doSelectBrand = function(){
			//id是值 name是显示
			GoDialog.showSelect("请选择品牌",$scope.brand_items,$scope.input.brand,function(data){
				$scope.input.brand_id = data.id;
				$scope.input.brand_name = data.name;
				$scope.input.brand = data;
			});
		}
		$scope.doSelectCat1 = function(){
			//id是值 name是显示
			GoDialog.showSelect("大分类",$scope.cat1_items,$scope.input.cat1,function(data){
				$scope.input.cat1 = data;
			});
		}
		$scope.doSelectCat2 = function(){
			//id是值 name是显示
			GoDialog.showSelect("中分类",$scope.cat2_items,$scope.input.cat2,function(data){
				$scope.input.cat2 = data;
			});
		}
		$scope.doSelectCat3 = function(){
			//id是值 name是显示
			GoDialog.showSelect("小分类",$scope.cat3_items,$scope.input.cat3,function(data){
				$scope.input.cat3 = data;
			});
		}
		//处理请联系
		$scope.dochecklink = function(data) {
			if(data.site_search_limit == 1) {
				for(var i = 0; i < data.products.length; i++) {
					if(data.products[i].store_type == 4) {
						data.products[i].limit = 1; //每个商品的不一样
						var brand_id = data.products[i].brand_id;
						data.products[i].concact = "";
						if(data.products[i].contact_list) {
							if(data.products[i].contact_list[brand_id]) {
								for(var j = 0; j < data.products[i].contact_list[brand_id].length; j++) {
									var phone = data.products[i].contact_list[brand_id][j];
									if(data.products[i].concact == "")
										data.products[i].concact = phone;
									else
										data.products[i].concact = data.products[i].concact + " / " + phone;
								}
							} else {
								data.products[i].concact = data.service_phone;
							}
						} else {
							data.products[i].concact = data.service_phone;
						}
					} else {
						data.products[i].limit = 0; //每个商品的不一样
					}
				}
			}
			return data;
		};
		//侦听输入变化 省份选择会覆盖其他
//		$scope.$watch("input.brand", function(newValue, oldValue) {
//			if(newValue == null || newValue == oldValue) return;
//			$scope.input.brand_id = newValue.id;
//		});

		//侦听排序变化，一定要避免刚初始化时也触发到该方法（避免重复请求），所以这里加了productsearch条件
		$scope.$watch("input.orderby", function(newValue, oldValue) {
			if(!newValue || newValue == oldValue||!$scope.productsearch) return;
			if(newValue == "9")
				$scope.input.xiaol = 1;
			else
				$scope.input.xiaol = -1;
			if(newValue == "4" || newValue == "5") {
				$scope.input.price = newValue == "4" ? 1 : 0;
			} else {
				$scope.input.price = -1;
			}
			$scope.goto_search();
		});
		
		//销量排序
		$scope.sort_xiaol = function() {
			$scope.input.xiaol = 1;
			$scope.input.orderby = "9";
			$scope.input.price = -1;
			$scope.goto_search();
		};
		//价格排序
		$scope.sort_price = function() {
			if($scope.input.price >= 0) {
				$scope.input.price = $scope.input.price == 0 ? 1 : 0;
				$scope.input.orderby = $scope.input.price == 1 ? "4" : "5";
			} else {
				$scope.input.price = 0;
				$scope.input.orderby = "5";
			}
			$scope.input.xiaol = -1;
			$scope.goto_search();
		};
		//打开右边的筛选菜单
		$scope.openRightMenu = function() {
			$ionicSideMenuDelegate.toggleRight();
		}
		//商品详情
		$scope.onshow_detail = function(goods_id, store_id, limit) {
			GoPage.go_states("productdetail", { "goods_id": goods_id, "store_id": store_id, "type": 'goods', 'limit': limit });
		}
		//门店详情
		$scope.onshow_store = function(store_id) {
			GoPage.go_states("first", { "index": 0, "store_id": store_id, "coupon_id": 0 });
		};
		//显示模式
		$scope.openShowImg = function() {
			if($scope.input.showimg == 0)
				$scope.input.showimg = 1;
			else
				$scope.input.showimg = 0;
		};
		//上拉加载更多必须定义
		$scope.isLoad = false;
		//下拉刷新 判断哪个模块进行刷新
		$scope.doRefresh = function() {
			$scope.isLoad = true;
			$scope.goto_search(function() {
				$scope.$broadcast('scroll.refreshComplete');
				$timeout(function() {
					$scope.isLoad = false;
				}, 1000);
			});
		};
		//加载更多
		$scope.doRefreshMore = function() {
			$scope.isLoad = true;
			$scope.goto_more_search(function() {
				$scope.$broadcast('scroll.infiniteScrollComplete');
				$timeout(function() {
					$scope.isLoad = false;
				}, 2000);
			});
		};
		//滚动侦听
		$scope.doShowTop = function(name, index) {
			var delegate = $ionicScrollDelegate.$getByHandle(name);
			if(delegate.getScrollPosition() == undefined) return;
			var scrollTop = delegate.getScrollPosition().top;
			//分类
			$scope.$apply(function() {
				if($window.innerHeight <= delegate.getScrollPosition().top) {
					$scope.showtop999 = "show";
				} else {
					$scope.showtop999 = "hide";
				}
			});
		};
		//回到顶部
		$scope.doScrollToTop = function(name, index) {
			$ionicScrollDelegate.$getByHandle(name).scrollTop(true);
		};
	}

	controller.$inject = ['$scope', 'Productsearch','GoDialog', '$window', '$stateParams', '$ionicScrollDelegate', '$ionicSideMenuDelegate', 'GoPage', 'Auth', '$timeout', 'GoCatTypeAuth'];

	return app.registerController("productsearchctrl", controller);
});